(function ($, w) {
    /**
     * 封装ajax数据交互
     */
    var _defaults = {
        type: "Get",
        dataType: "json",
        checkPermission: true,
        traditional: false,
        async: true,
        contentType: "application/json; charset=utf-8"
    };

    $.getJsonData = function (url, params, opts) {
        var dfd = $.Deferred();
        opts = $.extend({}, _defaults, opts);
        $.ajax({
            url: url,
            type: opts.type,
            headers: {
                Ticket: $.cookie ? $.cookie("ticket") : ""
            },
            dataType: opts.dataType,
            async: opts.async,
            contentType: opts.contentType,
            data: opts.type.toLowerCase() == "get" ? params : JSON.stringify(params),
            traditional: opts.traditional
        }).done(function (data, textStatus, jqXHR) {
            if (data.throwable != null) {
                dfd.reject(data, textStatus, jqXHR);
            }
            if (opts.checkPermission) {
                var ssoLoginUrl = jqXHR.getResponseHeader("SSO-Login-Url") || '';
                //需要跳转
                if (ssoLoginUrl.length > 0) {
                    var href = window.location.href;
                    if (href.indexOf("?") > 0) {
                        href = href.substring(0, href.indexOf("?"));
                    }
                    window.location.href = ssoLoginUrl + (ssoLoginUrl.indexOf("?") > 0 ? "&" : "?") + "callback=" + href;
                    return;
                }

                var permissionNotAllowedHeader = jqXHR.getResponseHeader("Permission-Not-Allowed") || '';
                //无权限
                if (permissionNotAllowedHeader.length > 0) {
                    layui.layer.msg("您无权限操作", {icon: 2});
                    return;
                }

                dfd.resolve(data);
            } else {
                dfd.resolve(data, textStatus, jqXHR);
            }
        }).fail(function (jqXHR, textStatus, errorThrown) {
            dfd.reject(jqXHR, textStatus, errorThrown);
        });

        return dfd.promise();
    };

    $.getHtmlContent = function (url) {
        var dfd = $.Deferred();
        $.ajax({
            url: url,
            type: "Get",
            async: true,
            contentType: "text/html;charset=utf-8"
        }).done(function (data, textStatus, jqXHR) {
            if (data.throwable != null) {
                dfd.reject(data, textStatus, jqXHR);
            }
            dfd.resolve(data);

        }).fail(function (jqXHR, textStatus, errorThrown) {
            dfd.reject(jqXHR, textStatus, errorThrown);
        });

        return dfd.promise();
    };

    $.fn.formData = function (initData) {
        var $inputs = $(':input', this).not(
            ':button, :submit, :reset,[name="repassword"]');
        var data = initData || {};
        $.each($inputs, function (index, input) {
            var $input = $(input);
            data[$input.attr("name")] = $input.val();
        });

        return data;
    };

    $.hashCode = function (str) {
        var hash = 0;
        if (str.length == 0) return hash;
        for (i = 0; i < str.length; i++) {
            char = str.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash; // Convert to 32bit integer
        }
        return hash;
    }

    var app = {pageData: {}, pageEvents: {}, tabs: {}};

    /**
     * 获取映射关系，返回关联和未关联的映射关系
     * @param url 查询的url
     * @param searchParams 查询参数
     * @param page 页面名称
     * @returns {*}
     */
    app.getRel = function (url, searchParams, page) {
        var dfd_one = $.Deferred();
        var dfd_second = $.Deferred();
        var result_dfd = $.Deferred();

        var relatedSearchParams = JSON.parse(JSON.stringify(searchParams));
        var noRelatedSearchParams = JSON.parse(JSON.stringify(searchParams));
        relatedSearchParams.searchType = "RELATED";
        noRelatedSearchParams.searchType = "UNRELATED";

        $.getJsonData(url, relatedSearchParams).done(function (data) {
            dfd_one.resolve(data);
        });
        $.getJsonData(url, noRelatedSearchParams).done(function (data) {
            dfd_second.resolve(data);
        });


        $.when(dfd_one, dfd_second).done(function (related, unRelated) {
            var relatedItems = related.result.items || [];
            var unRelatedItems = unRelated.result.items || [];

            //以json格式存储已经关联的映射关系
            var relatedInJson = {};
            $.each(relatedItems, function (index, e) {
                relatedInJson[e.id] = '';
            });
            app.pageData[page] = $.extend({}, app.pageData[page], searchParams, {related: relatedInJson});
            result_dfd.resolve(relatedItems || [], unRelatedItems || []);
        });

        return result_dfd;
    };

    //设置操作行记录数据
    app.setRecord = function (page, data) {
        app.pageData[page] = $.extend({}, app.pageData[page], {"record": data});
    };

    /**
     * 更新映射关系
     * @param url 更新接口地址
     * @param id 主维度标识
     * @param oldRelated 原始的关联关系
     * @param related 新的关联关系
     * @param page 页面名称
     * @returns {*}
     */
    app.updateRel = function (url, page) {
        //json格式
        var oldRelated = app.pageData[page].related;
        //json格式
        var related = {};
        $("#bootstrap-duallistbox-selected-list_doublebox option").each(function (index, e) {
            related[e.value] = '';
        });

        var newRelIds = [], deleteRelIds = [];
        var dfd = $.Deferred();
        $.each(oldRelated, function (index, e) {
            if (index != undefined && related[index] === undefined) {
                deleteRelIds.push(index);
                oldRelated[index] = undefined;
            }
        });

        $.each(related, function (index, e) {
            if (index != undefined && oldRelated[index] === undefined) {
                newRelIds.push(index);
            }
        });

        $.getJsonData(url, {
            newRelIds: newRelIds,
            deleteRelIds: deleteRelIds,
            id: app.pageData[page].record.id
        }, {type: "Post"}).done(function (data) {
            dfd.resolve(data);
        });

        return dfd.promise();
    };

    app.showError = function (msg) {
        var layer = layui.layer;
        layer.msg(msg, {icon: 2});
    };

    app.showSuccess = function () {
        var layer = layui.layer;
        layer.closeAll();
        layer.msg('操作成功', {icon: 6});
    };

    //拉取app列表
    app.fetchApps = function () {
        if (!app.appList) {
            $.getJsonData("/sso/apps", {}, {async: false}).done(function (data) {
                app.appList = data.result.items;
            });
        }
        return app.appList;
    };

    /**
     * 根据id获取应用
     * @param appId
     * @returns {*}
     */
    app.getAppById = function (appId) {
        if (!app.appList) {
            app.appList = app.fetchApps();
        }
        if (app.appList) {
            var matchedApp;
            $.each(app.appList, function (i, e) {
                if (appId == e.id) {
                    matchedApp = e;
                }
            });
            return matchedApp;
        }
    };

    /**
     * 渲染下拉框选项
     * @param items 数据（json数组）
     * @param selectedVal 选中的值
     * @param value value键，默认code
     * @param description 显示值的键，默认description
     * @param needAll 是否需要所有的选项，默认需要
     * @returns {*}
     */
    app.renderSelectOptionsTemplate = function (items, selectedVal, value, description, needAll) {
        var dfd = $.Deferred();
        value = value || "code";
        description = description || "description";
        items = JSON.parse(JSON.stringify(items || []));
        if (needAll || needAll === undefined) {
            items.splice(0, 0, {code: '', description: "不限"});
        }

        $.each(items, function (index, item) {
            item.code = item[value];
            item.description = item[description];
        });

        layui.laytpl($("#selectOptionsTemplate").html()).render({
            items: items,
            selectedVal: selectedVal
        }, function (content) {
            dfd.resolve(content);
        });

        return dfd.promise();

    };

    /**
     * 根据url将页面显示到标签页
     * @param url 路径
     * @param name 菜单名称
     * @param forceRefresh 是否需要强制刷新
     */
    app.showPage = function (url, name, forceRefresh) {
        var hashCode = $.hashCode(name);
        //如果tab已经打开了
        var $tab = $(".moon-tab [lay-id='" + hashCode + "']");
        if ($tab.length == 1) {
            if (forceRefresh) {
                $.getHtmlContent(url).done(function (data) {
                    var tabIndex = $(".moon-tab li").index($tab);
                    $(".moon-tab-content .layui-tab-item:eq(" + tabIndex + ")").html(data);
                });
            }
            layui.element.tabChange('moon-tab', hashCode);
        } else {
            $.getHtmlContent(url).done(function (data) {
                layui.element.tabAdd('moon-tab', {
                    title: name
                    , content: data
                    , id: hashCode
                });
                layui.element.tabChange('moon-tab', hashCode);
            });
        }
        app.tabs[hashCode] = {url: url, name: name};
    };

    /**
     * 刷新当前选中的标签
     */
    app.refreshSelectedTabContent = function () {
        var $selectedTab = $(".moon-tab .layui-this");
        var layId = $selectedTab.attr("lay-id");
        var menuInfo = app.tabs[layId];
        if (!menuInfo) return;
        app.showPage(menuInfo.url, menuInfo.name, true);
    };

    $(function () {
        $(document).on("click", ".btn-cancel", function () {
            var layer = layui.layer;
            layer.closeAll();
        });
    });

    /**
     * 绑定页面事件
     * @param callback
     */
    app.bindPageEvents = function (pageName, callback) {
        //如果已经绑定，则无需再次绑定
        if (app.pageEvents[pageName]) {
            return;
        }
        if (typeof callback == "function") {
            callback.call(app);
        }
        app.pageEvents[pageName] = true;
    };
    w.app = app;
})(jQuery, window);